<?php
class c_video extends CI_Controller{
    
    private $data;
    
    public function __construct(){
        parent::__construct();
        $this->load->helper("url");
        $this->load->model('m_model');
    }
    
    public function index(){
        $this->data["page_title"] = "Trang chủ";
        $this->data["page_left"] = "v_video";
        $this->data["page_right"] = "v_right_side_home";

        $this->renderRightBar();
        $newsDetail = $this->renderContent();

        $this->data["content"] = $newsDetail;
        $this->load->view("v_masterpage.php", $this->data);
    }

    private function renderContent(){
        $pageIndex = isset($_GET["page"]) ? $_GET["page"] : 1;
        $pageSize = 20;
        $listVideo = $this->m_model->getListVideoByPage($pageIndex - 1, $pageSize);
        $numberOfPage = ceil(count($listVideo) / $pageSize);
        
        $this->data['listVideo'] = $listVideo;
        $this->data['pagingVideo'] = $this->paging("/video", $numberOfPage, $pageIndex);
    }

    private function renderRightBar(){
        $bestNews = $this->m_model->getBestNewsRead();
        $this->data["listBestNews"] = $bestNews;
        
        $bestVideo = $this->m_model->getBestViewVideo();
        $this->data["listBestVideo"] = $bestVideo;
    }
    
    private function paging($pathInfo, $numberOfPage, $currentPage){
        $prevPage = $currentPage == 1 ? 1 : $currentPage - 1;
        $nextPage = $currentPage == $numberOfPage ? $numberOfPage : $currentPage + 1;
        $lastPage = $numberOfPage;

        $start_page = 1;
        $end_page = $numberOfPage;
        if($numberOfPage > 5){
            $start_page = $currentPage - 2 < 1 ? 1 : $currentPage - 2;
            $end_page = $currentPage + 2 > $numberOfPage ? $numberOfPage : $currentPage + 2;
        }

        $html = "<span class='other_page'><a href='" . $pathInfo . "?page=1'>Đầu</a></span>"
            . "<span class='other_page'><a href='" . $pathInfo . "?page=" . $prevPage . "'>Trước</a></span>";
        for($i=$start_page; $i<=$end_page; $i++){
            if($i == $currentPage){
                $html .= "<span class='current_page'>" . $i . "</span>";
            }
            else{
                $html .= "<span class='other_page'><a href='" . $pathInfo . "?page=" . $i . "'>" . $i . "</a></span>";
            }
        }
        $html .= "<span class='other_page'><a href='" . $pathInfo . "?page=" . $nextPage . "'>Sau</a></span>"
            . "<span class='other_page'><a href='" . $pathInfo . "?page=" . $lastPage . "'>Cuối</a></span>";

        return $html;
    }
    
}